<template>
  <div class="knowledge-container">
    <!-- 知识库列表 -->
    <el-card class="mb-4">
      <div class="flex justify-between items-center mb-2">
        <h2>知识库管理</h2>
        <el-button type="primary" @click="openEdit()">新增知识库</el-button>
      </div>

      <el-table :data="knowledgeList" stripe>
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column prop="name" label="名称"/>
        <el-table-column prop="description" label="描述"/>
        <el-table-column prop="embeddingModel" label="向量模型"/>
        <el-table-column prop="topK" label="TopK" width="80"/>
        <el-table-column prop="similarityThreshold" label="阈值" width="100"/>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="openEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="primary" @click="openDocs(scope.row)">文档</el-button>
            <el-button size="small" type="danger" @click="remove(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 知识库新增/编辑对话框 -->
    <el-dialog v-model="editVisible" title="知识库信息" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="名称"><el-input v-model="editForm.name" /></el-form-item>
        <el-form-item label="描述"><el-input v-model="editForm.description" type="textarea" /></el-form-item>
        <el-form-item label="向量模型">
          <el-select v-model="editForm.embeddingModel" placeholder="请选择模型"  @change="setModel">
            <el-option
            v-for="model in modelList"
            :label="model.name"
            :value="model.id"
          />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="向量模型">
          <el-input v-model="editForm.embeddingModel" />
        </el-form-item>
        <el-form-item label="模型ID"><el-input v-model="editForm.embeddingModelId" /></el-form-item> -->
        <el-form-item label="TopK"><el-input-number v-model="editForm.topK" :min="1" /></el-form-item>
        <el-form-item label="阈值"><el-input-number v-model="editForm.similarityThreshold" :step="0.01" /></el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="editForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>

    <!-- 文档管理对话框 -->
    <el-dialog v-model="docVisible" title="知识库文档" width="800px">
      <div class="mb-4 flex gap-4">
        <el-upload
          :action="`http://192.168.2.13:8081/ai/knowledge/${currentKnowledge?.id}/uploadFile`"
          :show-file-list="false"
          :on-success="loadDocuments"
        >
          <el-button type="primary">上传文件</el-button>
        </el-upload>

        <el-input v-model="urlInput" placeholder="输入文档URL" style="width: 300px"/>
        <el-button type="success" @click="uploadUrl">上传URL</el-button>
      </div>

      <el-table :data="documentList" stripe>
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column prop="name" label="文档名称"/>
        <el-table-column prop="url" label="URL" />
        <el-table-column prop="contentLength" label="字数" width="100"/>
        <el-table-column prop="tokens" label="Tokens" width="100"/>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewSlices(scope.row)">查看切片</el-button>
          </template>
        </el-table-column>

      </el-table>

      <template #footer>
        <el-button @click="docVisible = false">关闭</el-button>
      </template>
    </el-dialog>
<!-- 文档切片查看弹窗 -->
    <el-dialog v-model="sliceDialogVisible" title="文档切片列表" width="800px">
      <el-collapse>
        <el-collapse-item
          v-for="slice in sliceList"
          :key="slice.id"
          :title="`切片 #${slice.id}`"
        >
          <div class="slice-content">
            {{ slice.content }}
          </div>
        </el-collapse-item>
      </el-collapse>

      <template #footer>
        <el-button @click="sliceDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import { ModelApi, ModelVO } from '@/api/ai/model/model'

const modelList = ref([] as ModelVO[]); // API 密钥列表
const knowledgeList = ref([]);
const documentList = ref([]);

const editVisible = ref(false);
const docVisible = ref(false);

const editForm = ref({});
const currentKnowledge = ref(null);
const urlInput = ref("");
const sliceDialogVisible = ref(false);
const sliceList = ref([]);

// 查看切片
const viewSlices = async (doc:any) => {
  if (!currentKnowledge.value) return;
  try {
    const res = await axios.get(`http://192.168.2.13:8081/ai/knowledge/${currentKnowledge.value.id}/documents/${doc.id}/slices`);
    // 假设返回 [{ index: 1, content: 'xxx' }, ...]
    sliceList.value = res.data;
    sliceDialogVisible.value = true;
  } catch (err) {
    console.error(err);
    ElMessage.error("获取切片失败");
  }
};


const setModel = (val:any) => {
  const model = modelList.value.find(m => m.id === val)
  if(model) {
    editForm.value.embeddingModel = model.name
    editForm.value.embeddingModelId = model.id
  }
}

// 获取知识库列表  http://192.168.2.13:8081/ai
const loadKnowledge = async () => {
  const res = await axios.get("http://192.168.2.13:8081/ai/knowledge/list");
  knowledgeList.value = res.data;
};

// 打开编辑框
const openEdit = async(row) => {
  editForm.value = row ? { ...row } : { status: 1, topK: 3, similarityThreshold: 0.7 };
  editVisible.value = true;
      // 获得下拉数据
  const keyData =  await ModelApi.getModelList({})
  console.log(keyData);
  modelList.value = keyData.data
};

// 保存知识库
const save = async () => {
  await axios.post("http://192.168.2.13:8081/ai/knowledge/saveOrUpdate", editForm.value);
  ElMessage.success("保存成功");
  editVisible.value = false;
  loadKnowledge();
};

// 删除知识库
const remove = async (id) => {
  await ElMessageBox.confirm("确定删除该知识库吗？");
  await axios.delete(`http://192.168.2.13:8081/ai/knowledge/delete/${id}`);
  ElMessage.success("删除成功");
  loadKnowledge();
};

// 打开文档管理
const openDocs = async (row) => {
  currentKnowledge.value = row;
  docVisible.value = true;
  loadDocuments();
};

// 加载文档
const loadDocuments = async () => {
  if (!currentKnowledge.value) return;
  const res = await axios.get(`http://192.168.2.13:8081/ai/knowledge/${currentKnowledge.value.id}/documents`);
  documentList.value = res.data;
};

// 上传URL
const uploadUrl = async () => {
  if (!urlInput.value) {
    ElMessage.warning("请输入URL");
    return;
  }
  await axios.post(`http://192.168.2.13:8081/ai/knowledge/${currentKnowledge.value.id}/uploadUrl`, {
    url: urlInput.value,
  });
  ElMessage.success("上传成功");
  urlInput.value = "";
  loadDocuments();
};

onMounted(() => {
  loadKnowledge();
});
</script>

<style scoped>
.knowledge-container {
  padding: 20px;
}
.mb-4 {
  margin-bottom: 16px;
}
</style>
